package base.core.config;

import base.core.security.TokenInfo;

import org.springframework.scheduling.annotation.Async;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import lombok.SneakyThrows;

/**
 * 异步方法
 * Pengwei
 * 2022/2/22 21:42
 */
@Service
public class AsyncService {

    @Async
    public void run(AsyncDoing asyncDoing) {
        asyncDoing.runable();
    }

    @Async
    @SneakyThrows
    public void run(long millis, AsyncDoing asyncDoing) {
        Thread.sleep(millis);
        asyncDoing.runable();
    }

    @Async
    public void run(TokenInfo tokenInfo, AsyncDoing asyncDoing) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(tokenInfo, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        asyncDoing.runable();
    }

    @Async
    @SneakyThrows
    public void run(long millis, TokenInfo tokenInfo, AsyncDoing asyncDoing) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(tokenInfo, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        Thread.sleep(millis);
        asyncDoing.runable();
    }

    public interface AsyncDoing {
        void runable();
    }
}
